package cn.zysuyuan.item.service.impl;

import cn.zysuyuan.common.entity.Constant;
import cn.zysuyuan.common.entity.PageResult;
import cn.zysuyuan.common.utils.UUIDUtil;
import cn.zysuyuan.item.entity.Medicinal;
import cn.zysuyuan.item.entity.ProductBase;
import cn.zysuyuan.item.entity.ProductBaseImg;
import cn.zysuyuan.item.mapper.MedicinalMapper;
import cn.zysuyuan.item.mapper.ProductBaseImgMapper;
import cn.zysuyuan.item.mapper.ProductBaseMapper;
import cn.zysuyuan.item.mapper.ProductbaseMedicinalGoneMapper;
import cn.zysuyuan.item.service.MedicinalProductBaseService;
import cn.zysuyuan.item.service.ProductBaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author flypig
 * @version 1.0
 * @date 2019-11-22 20:31
 */

@Service
public class ProductBaseServiceImpl implements ProductBaseService {

    @Autowired
    private ProductBaseMapper productBaseMapper;

    @Autowired
    private ProductBaseImgMapper productBaseImgMapper;

    @Autowired
    private MedicinalMapper medicinalMapper;

    @Autowired
    private MedicinalProductBaseService medicinalProductBaseService;

    @Autowired
    private ProductbaseMedicinalGoneMapper productbaseMedicinalGoneMapper;

    @Override
    public PageResult<ProductBase> selectList(Map<String, Object> map) {

        // 将省市区拼接到一起，再查询
        String bProvinceSeek = (String) map.get("bProvinceSeek");
        String bCitySeek = (String)map.get("bCitySeek");
        String bRegionSeek = (String)map.get("bRegionSeek");
        String bPosition = "";
        if(bProvinceSeek !=null && !"".equals(bProvinceSeek)){
            bPosition =bProvinceSeek;
        }
        if(bCitySeek !=null && !"".equals(bCitySeek)){
            bPosition =bPosition+"|"+bCitySeek;
        }
        if(bRegionSeek !=null && !"".equals(bRegionSeek)){
            bPosition =bPosition+"|"+bRegionSeek;
        }

        map.put("bPosition", bPosition);
        List<ProductBase> productBases = this.productBaseMapper.selectList(map);
        // 将查询到的地址的'|'换位空格，并将地址拆分为省、市、区
        if(productBases != null && productBases.size() > 0) {
            for (int i = 0; i <productBases.size(); i++) {
                String[] positions = productBases.get(i).getbPosition().split("\\|");
                if (positions != null && positions.length > 0) {
                    for (int j = 0; j < positions.length; j++) {
                        switch (j){
                            case 0:
                                // 省
                                productBases.get(i).setbProvince(positions[j]);
                                break;
                            case 1:
                                // 市
                                productBases.get(i).setbCity(positions[j]);
                                break;
                            case 2:
                                // 区
                                productBases.get(i).setbRegion(positions[j]);
                                break;
                        }
                    }
                }
                // 将'|'替换为空格
                productBases.get(i).setbPosition(productBases.get(i).getbPosition().replace("|", " "));
            }
        }
        return new PageResult<ProductBase>(productBases);
    }

    // 查看基地图片
    @Override
    public PageResult<ProductBaseImg> selectListImg(String id) {
        List<ProductBaseImg> productBaseImgs = productBaseImgMapper.selectList(id);
        return new PageResult<ProductBaseImg>(productBaseImgs);
    }

    @Override
    public int insert(ProductBase productBase) {
        productBase.setId(UUIDUtil.uuid());
        productBase.setbPosition(productBase.getbProvince()+ "|" + productBase.getbCity()+"|"+productBase.getbRegion());
        productBase.setbCreateTime(new Date());
        return productBaseMapper.insert(productBase);
    }

    @Override
    public int update(ProductBase productBase) {
        String positions = productBase.getbProvince();
        if (productBase.getbCity() != null && !"".equals(productBase.getbCity())) {
            positions = positions + "|" + productBase.getbCity();
        }
        if (productBase.getbRegion() != null && !"".equals(productBase.getbRegion())) {
            positions = positions + "|" + productBase.getbRegion();
        }
        productBase.setbPosition(positions);
        return productBaseMapper.update(productBase);
    }

    @Override
    public int delete(String id) {
        // 遍历删除基地图片
        List<ProductBaseImg> listBH = productBaseImgMapper.selectList(id);
        if (listBH != null && listBH.size() > 0){
            for (int i = 0; i < listBH.size(); i++) {
                deleteImgLocation(listBH.get(i).gettImgId());
            }
        }
        // 删除excle，暂时没加上传excle的功能，等以后相加再加，反正跟上传图片差不多，不过中药那个项目就有，你想加就加咯，手动狗头🐕
        //TODO delete excle files

        // 删除药材基地关联表中与这个基地相关的记录
        medicinalProductBaseService.deleteProductBase(id);
        // 删除表中图片路径信息
        productBaseImgMapper.deleteProductBaseImg(id);
        // 删除原料去向
        productbaseMedicinalGoneMapper.deleteProductbaseRefer(id);

        return productBaseMapper.delete(id);
    }

    /**
     * 删除服务器上传的文件、图片
     * @param imgpath
     */
    public void  deleteImgLocation(String imgpath) {
        String path = Constant.IMG_PATH + imgpath;
        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
    }


    @Override
    public List<String> selectAllMedicinal() {
        return medicinalMapper.selectAllMedicinal();
    }

    /**
     * 保存基地图片
     * @param files
     * @param request
     * @param map
     * @return
     */
    @Override
    public Map<String, Object> saveImg(MultipartFile[] files, HttpServletRequest request, Map<String, Object> map) {
        Map<String,Object> maps = new HashMap<String, Object>();
        System.out.println("数据长度" + files.length);
        System.out.println("基地id：" + (String)map.get("id"));
        try {
            // 判断文件数组是否为空
            if (files == null || files.length < 1) {
                maps.put("code",false);
            } else {
                System.out.println("有数据");
                //判断是否有路径
                String path = Constant.IMG_PATH_FILE;
                if (!new File(path).exists()) {
                    new File(path).mkdirs();
                }
                // 遍历图片文件
                for (int i = 0; i < files.length; i++) {
                    MultipartFile file = files[i];
                    // 将图片文件保存到服务器，同时返回上传后图片的名字
                    String image = uploadFile(file,path,map);
                    ProductBaseImg productBaseImg = new ProductBaseImg();
                    productBaseImg.setId(UUIDUtil.uuid());
                    productBaseImg.settImgId(image);
                    productBaseImg.settProductbaseId((String)map.get("id"));
                    productBaseImgMapper.insert(productBaseImg);
                    System.out.println("上传成功");
                }
                maps.put("code",true);
            }
        } catch (IOException e) {
            maps.put("code",false);
            e.printStackTrace();
        }
        return maps;
    }

    @Override
    public List<ProductBase> selectAllProductName() {
        return productBaseMapper.selectAll();
    }

    public static String uploadFile(MultipartFile file,String path,Map<String, Object> map) throws IOException {
        String name = file.getOriginalFilename();
        String suffixName = name.substring(name.lastIndexOf("."));
        // 生成图片id
        String imgid = UUIDUtil.uuid();
        String fileName = imgid + suffixName;
        File tempFile = new File(path,fileName);
        if(!tempFile.getParentFile().exists()){
            tempFile.getParentFile().mkdir();
        }
        if(tempFile.exists()){
            tempFile.delete();
        }
        tempFile.createNewFile();
        file.transferTo(tempFile);
        return tempFile.getName();
    }


}
